
import { viewModel } from 'nc-lightapp-front';
let { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;

//获取当前表格所有数据
export function getTransferTableValue(id) {
    return this.state.transferTable[id];
}

/*
*   获取表格所有勾选数据
* */
export function getTransferTableSelectedValue() {
    let { allSelected, ...transfers } = this.state.transferTable;
    let result = {};
    for(let key in transfers){
        if (!result.hasOwnProperty(key)){
            result[key] = [];
        }
        let masterSelData = transfers[key].selected.selectedData.masterSelData
        let childSelData = transfers[key].selected.selectedData.childSelData;
        let bodyTableId = transfers[key][key].bodyTableId;
        if(transfers[key][key].tableType === 'simple'){ // 单表
            for(let id in masterSelData){
                result[key].push(masterSelData[id].data);
            }
        }else{ //主子表
            for(let headKey in childSelData){
                let headArr = [],bodyArr = [];
                if (headArr.length == 0){
                    headArr.push({
                        values: masterSelData[headKey].data
                    });
                }
                Object.values(childSelData[headKey]).forEach(item => {
                    let val = item.data.values || item.data;
                    bodyArr.push({
                        values: val
                    });
                });
                result[key].push({
                    head: {
                        [key]: {
                            rows: headArr
                        }
                    },
                    body: {
                        [bodyTableId]: {
                            rows: bodyArr
                        }
                    }
                })
            }
        } 
        
        
        
    }
    return result;
}

/*
*   更新外层表格数据
*   @ newData  外层表格数据
*   @ rowId  主表主键字段 如果是全部多来源需要传数组，其他页签主表主键放到数组中
*   @ childId  子表主键字段 如果是全部多来源需要传数组，其他页签子表主键放到数组中
* */
export function setTransferTableValue(id, childCode, newData, rowId, childId) {
    let outerData = [];
    let bodyData = {};
    let rowKey,childKey;
    if (typeof rowId === 'string' && typeof childId === 'string'){
        rowKey = rowId;
        childKey = childId;
    }
    //表格类型为单表
    if (this.state.transferTable[id][id].tableType === 'simple'){
        newData.rows.map((item,index) => {
            item.rowId = item.values[rowKey].value;
            item.values.key = item.rowId;
            item.values.rowIndex = index;
            outerData.push(item);
        });
    }else{
        newData.forEach((item, index) => {
            let val = item.head[id].rows[0];
            //全部多来源主键字段不唯一，需要传入其他页签主键字段
            if (Array.isArray(rowId)){
                rowId.map(id => {
                    if (Object.keys(val.values).includes(id)){
                        rowKey = id;
                    }
                });
            }
            if (!val.rowId && val.rowId !== 0) {
                if (!val.values[rowKey]) {
                    console.error('setTransferTableValue方法中，主表Id没找到');
                    return false
                }
                val.rowId = val.values[rowKey].value;
            }
            val.values.key = val.rowId;
            val.values.rowIndex = index;
            outerData.push(val);
    
            let bodyDataRows = item.body[childCode].rows.map((elem, ii) => {
                //全部多来源主键字段不唯一，需要传入其他页签子表主键字段
                if (Array.isArray(childId)) {
                    childId.map(cid => {
                        if (Object.keys(elem.values).includes(cid)) {
                            childKey = cid;
                        }
                    });
                }
                if (!elem.childId && elem.childId !== 0) {
                    if (!elem.values[childKey]) {
                        console.error('setTransferTableValue方法中，子表Id没找到');
                        //return false
                    }
                    elem.childId = elem.values[childKey] && elem.values[childKey].value;
                }
                elem.values.key = elem.childId;
                elem.values.rowIndex = ii;
                elem.values.parentRowId = val.rowId;
                return elem;
            })
            bodyData[val.rowId] = { rows: bodyDataRows };
        });
    }

    this.serverOuterData = {
        ...this.serverOuterData,
        [id]: JSON.parse(JSON.stringify(outerData))
    };
    this.serverBodyData = {
        ...this.serverBodyData,
        [id]: JSON.parse(JSON.stringify(bodyData))
    }
    
    this.state.transferTable[id][id].masterId = rowKey;
    this.state.transferTable[id][id].childId = childId;
    this.state.transferTable[id][id].outerData = outerData;
    this.state.transferTable[id][id].bodyData = {
        data: bodyData
    };

    this.setState({
        transferTable: this.state.transferTable
    });
}

/*
*   设置展开的子表数据
*   @ record  主表当前行信息
*   @ column  子表列模板信息
*   @ datas  子表数据
*   @ rowId  子表行 主键字段
* */
export function setChildTransferTableData(id, record, datas, rowId) {
    let table = this.state.transferTable[id][id];
    // let checkedArrayChild = [];//子表每行勾选状态
    let key = record.key;
    let rowIndex = record.rowIndex;
    datas.rows.map((val, index) => {
        if (!val.rowId && val.rowId !== 0) {
            if (!val.values[rowId]) {
                console.error('传入数据中没有找到子表Id');
                return false
            }
            val.rowId = val.values[rowId].value;
        }
        val.values.key = val.rowId;
        // if (table.mainCheckObj.checkedArray[rowIndex]) {
        //     checkedArrayChild.push(true)
        // } else {
        //     checkedArrayChild.push(false)
        // }
    });

    //table.bodyData.data[key] = datas;

    if (this.state.transferTable[id].selected.selectedData.masterSelData[key]) {
        this.state.transferTable[id].selected.selectedData.childSelData[key] = {};
        datas.rows.map((item, index) => {
            this.state.transferTable[id].selected.selectedData.childSelData[key][item.values.key] = {
                sel: true,
                data: item
            }
        })
    }
    this.setState({
        transferTable: this.state.transferTable
    });

    // // 根据主表当前行是否勾选，设置子表复选框 勾选
    // if (!table.childCheckObj.hasOwnProperty(key)) {
    //     table.childCheckObj[key] = {
    //         checkedAllChild: table.mainCheckObj.checkedArray[rowIndex],
    //         checkedArrayChild: checkedArrayChild
    //     };
    // }

    // this.setState({
    //     transferTable: this.state.transferTable
    // });
}

/*
*   更新主子拉平表格数据
*   @ data  主子拉平表格数据
*   @ rowId  主表主键字段
*   @ headId  主表id字段
* */
// export function setFullTransferTableValue(id, newData, rowId, headId) {
//     newData.rows.map((val, index) => {
//         if (!val.rowId && val.rowId !== 0) {
//             if (!val.values[rowId]) {
//                 console.error('setFullTransferTableValue方法中，rowId没找到');
//                 return false
//             }
//             if (!val.values[headId]) {
//                 console.error('setFullTransferTableValue方法中，headId没找到');
//                 return false
//             }
//             val.rowId = val.values[rowId].value;
//             val.headId = val.values[headId].value;
//         }
//         val.values.key = val.rowId;
//         val.values.headKey = val.headId;
//         val.values.rowIndex = index;
//     });
//     this.state.transferTable[id][id].fullData = newData.rows;
//     this.setState({
//         transferTable: this.state.transferTable
//     });
// }

//切换视图
export function changeViewType(id) {
    let { transferTable } = this.state;
    for (let key in transferTable){
        if (key !== 'allSelected'){
            transferTable[key][key].showFullTable = !transferTable[key][key].showFullTable;
        }else{
            transferTable[key].showFullTable = !transferTable[key].showFullTable;
        }
    }
    this.setState({
        transferTable: this.state.transferTable
    });
}



//----------------------------------转单左侧列表相关API---------------------------//

/*
*   更新转单数据
*   @selId  已选列表主子表id
*   @ data  转单列表数据
* */
export function setTransferListValue(id, data) {
    let transformForm = this.state.transferList[id].transformForm;
    let lists = [],
        completeArr = [];
    transformForm.listData.data = data;
    data && data.map(item => {
        lists.push({
            complete: false, //是否已处理
            data: item
        });
        completeArr.push(false);
    });

    transformForm.list = lists;
    transformForm.completeArr = completeArr;

    this.setState({
        transformForm
    },() => {
        this.onTransferItemSelected && 
        this.onTransferItemSelected(transformForm.list[0].data, transformForm.list[0].complete,transformForm.activeIndex);
    });
}

//获取已选列表显示状态
export function getSelectedListDisplay(id) {
    if(id === 'all'){ //全部多来源已选列表
        return this.state.transferTable.allSelected && this.state.transferTable.allSelected.selectedShow;
    }else if (this.state.transferTable[id] && this.state.transferTable[id].selected) {
        return this.state.transferTable[id] && this.state.transferTable[id].selected && this.state.transferTable[id].selected.selectedShow;
    }
}

//获取转单显示状态
export function getTransformFormDisplay(id) {
    if (this.state.transferList[id] && this.state.transferList[id].transformForm) {
        return this.state.transferList[id] && this.state.transferList[id].transformForm && this.state.transferList[id].transformForm.show;
    }
}

//获取转单列表数量
export function getTransformFormAmount(id) {
    return this.state.transferList[id] && this.state.transferList[id].transformForm.list.length;
}

//获取已选的主子表id
export function getTransferTableSelectedId() {
    let result = getGlobalStorage('sessionStorage', 'transferIds') && JSON.parse(getGlobalStorage('sessionStorage', 'transferIds'));
    return result;
}

//获取多来源已选的主子表id
export function getTransferTableMultiSelectedId() {
    let result = getGlobalStorage('sessionStorage', 'multiTransferIds') && JSON.parse(getGlobalStorage('sessionStorage', 'multiTransferIds'));
    return result;
}

//获取当前转单处理状态
//index:非必须 要查看转单的index
export function getTransformFormCompleteStatus(id, index) {
    let actIndex = index || this.state.transferList[id].transformForm.activeIndex;
    return this.state.transferList[id].transformForm.list[actIndex].complete;
}

/* 
*   返回待选列表
 */
export function returnTransferTableList(id) {
    let { transferList } = this.state;
    transferList[id].selected.selectedShow = false;
    transferList[id].transformForm.show = false;
    this.setState({
        transferList
    });
}

/* 
*   改变转单状态 
*   @status 转单状态 true:状态变为已转单 false:从转单列表移除该条数据
*   @headTableId 主表id
*   @childId 子表主键字段名
*   @index 当前操作数据的index
*   @onChange 操作成功后的回调函数
 */
export function setTransformFormStatus(headTableId, params) {
    let { status, index, onChange } = params;
    if (typeof status === 'undefined' || typeof headTableId === 'undefined') {
        return false;
    }
    let transferList = this.state.transferList[headTableId];
    // let table = transferList[headTableId];
    //let { transformForm } = transferList;
    //let { selectedData, masterCheckedId } = transferTable.selected;
    let { activeIndex, list, completeArr } = transferList.transformForm;
    let transformIndex = index || activeIndex;//不传index默认为当前操作的index
    if (status) { //状态变为已转单
        if (list[transformIndex]) {
            list[transformIndex].complete = true;
            completeArr[transformIndex] = true;
            transferList.transformForm.currentData = list[transformIndex].data;//当前操作的数据
        }
        // let oBodyData = table.bodyData.data;
        // //保存后删除待选/已选列表对应数据
        // for (let key in oBodyData){
        //     oBodyData[key].rows.map((item, i, array) => {
        //         if (item.rowId === transformForm.currentData[childId].value) {
        //             array.splice(i, 1);
        //         }
        //     });
        //     //子表无数据时删除主表
        //     if (oBodyData[key].rows.length === 0){
        //         table.outerData.map((val,i,array) => {
        //             if(val.rowId === key){
        //                 array.splice(i,1);
        //             }
        //         })
        //     }
        // }
    } else { //取消
        if (list.length > 0) {
            transferList.transformForm.currentData = list.splice(transformIndex, 1)[0].data;//取消的那条数据
            completeArr.splice(transformIndex, 1);
        }
        // //取消时删掉对应已选主表id
        // for (let key in selectedData.childSelData) {
        //     let curHeadId = Object.keys(selectedData.childSelData[key]).includes(transformForm.currentData[childId].value) ? key : null;
        //     if (masterCheckedId.indexOf(key) !== -1 && curHeadId === key){
        //         masterCheckedId.splice(masterCheckedId.indexOf(key),1);
        //     }
        // }
    }
    // //取消勾选状态
    // for (let key in selectedData.childSelData) {
    //     delete selectedData.childSelData[key][transformForm.currentData[childId].value];
    //     if (JSON.stringify(selectedData.childSelData[key]) === '{}') {
    //         delete selectedData.childSelData[key];
    //         //子表没有勾选数据时 取消主表勾选状态
    //         delete selectedData.masterSelData[key];
    //     }
    // }

    this.setState({
        transferList: this.state.transferList
    },
        () => {
            //有下一条数据跳至下一条数据
            if (list.length > 0) {
                this.transferTable.changeNextTransformForm(headTableId, status, onChange);
            } else {
                //当前只有一条数据则返回列表
                this.transferTable.returnTransferTableList(headTableId);
            }
        }
    );
}

/* 
*   批量改变转单状态
*   @headTableId 主表id
*   @status 转单状态 true:状态变为已转单 false:从转单列表移除该条数据
*   @selId 选中数据的id
*   @success 操作成功后的回调函数
 */
export function setMultiTransformFormStatus(headTableId, params) {
    let { status, selId, success } = params;
    if (typeof status === 'undefined' || typeof headTableId === 'undefined' || typeof selId === 'undefined') {
        return false;
    }
    let transferTable = this.state.transferTable[headTableId];
    let table = transferTable[headTableId];
    let { transformForm } = transferTable;
    let { selectedData, masterCheckedId } = transferTable.selected;
    let { activeIndex, list, completeArr } = transformForm;
    let oBodyData = table.bodyData.data;
    //批量保存
    if (Array.isArray(selId)) {
        selId.forEach(id => {
            if (status) {
                //保存后删除待选/已选列表对应数据
                for (let key in oBodyData) {
                    oBodyData[key].rows.map((item, i, array) => {
                        if (item.rowId === id) {
                            array.splice(i, 1);
                        }
                    });
                    //子表无数据时删除主表
                    if (oBodyData[key].rows.length === 0) {
                        table.outerData.map((val, i, array) => {
                            if (val.rowId === key) {
                                array.splice(i, 1);
                            }
                        })
                    }
                }
            } else {
                //取消时删掉对应已选主表id
                for (let key in selectedData.childSelData) {
                    let curHeadId = Object.keys(selectedData.childSelData[key]).includes(id) ? key : null;
                    if (masterCheckedId.indexOf(key) !== -1 && curHeadId === key) {
                        masterCheckedId.splice(masterCheckedId.indexOf(key), 1);
                    }
                }
            }

            //取消勾选状态
            for (let key in selectedData.childSelData) {
                delete selectedData.childSelData[key][id];
                if (JSON.stringify(selectedData.childSelData[key]) === '{}') {
                    delete selectedData.childSelData[key];
                    //子表没有勾选数据时 取消主表勾选状态
                    delete selectedData.masterSelData[key];
                }
            }

        });
    }
    if (typeof success === 'function') {
        success();
    }
}


/* 
*   切换到下一条转单钩子函数
*   @status 转单状态 true:状态变为已转单 false:从转单列表移除该条数据
 */
export function changeNextTransformForm(headTableId, status, callback) {
    let transferList = this.state.transferList[headTableId];
    let { transformForm } = transferList;
    let { activeIndex, list, completeArr } = transformForm;
    let currentIndex = activeIndex;
    let afterArr = completeArr.slice(activeIndex);
    let nextNotCompleteIndex = completeArr.indexOf(false, activeIndex);//下一个待处理转单
    let nextActiveIndex = nextNotCompleteIndex < 0 ? activeIndex : nextNotCompleteIndex;

    if (nextNotCompleteIndex < 0) {
        nextNotCompleteIndex = completeArr.indexOf(false);
        nextActiveIndex = completeArr.indexOf(completeArr[completeArr.findIndex((v, index) => index === activeIndex + 1)], activeIndex);
    }

    //没有待处理单据
    if (completeArr.every(item => item)) {
        //保存时保留在当前数据
        if (status) {
            nextActiveIndex = activeIndex;
        } else { //取消时没有待处理单据跳到第一条
            nextActiveIndex = 0;
        }
    } else {
        //有待处理数据时
        nextActiveIndex = nextNotCompleteIndex;
    }
    //如果找不到数组项 index设为数组的长度
    if (!transformForm.list[currentIndex]) {
        currentIndex = transformForm.list.length - 1;
    }
    transformForm.activeIndex = nextActiveIndex;
    this.setState({
        transferList: this.state.transferList
    },
        () => {
            if (callback) {
                let curData = transformForm.currentData;
                let nextData = transformForm.list[nextActiveIndex] && transformForm.list[nextActiveIndex].data;
                let nextStatus = transformForm.list[nextActiveIndex] && transformForm.list[nextActiveIndex].complete;
                callback(curData, nextData, activeIndex);
                this.onTransferItemSelected(
                    nextData, 
                    nextStatus,
                    this.state.transferList[headTableId].transformForm.activeIndex);
            };
        }
    );
}


/* 
*   根据index更新左侧列表数据
*   @id 列表Id  data:要更新的数据  index:要更新数据的index
*/
export function setTransferListValueByIndex(id, data, index) {
    let transformForm = this.state.transferList[id].transformForm;
    transformForm.list[index].data = data;
    this.setState({
        transferList: this.state.transferList
    })
}

/* 
*   有全部页签的多来源设置已选列表的数据
*   @headId 主表模板id
*   @bodyId 子表模板id
*   @data 接口返回的数据
*   @rowId 主表主键
*   @childId 子表主键
*
*/
export function setMultiSelectedValue(headId, bodyId, data, rowId, childId) {
    let { masterSelData, childSelData } = this.state.transferTable.allSelected.selectedData;
    data.map(item => {
        let headVal = item.head[headId].rows[0].values;
        let headIdVal;
        if (Array.isArray(rowId)){
            rowId.map(id => {
                if (headVal.hasOwnProperty(id)){
                    headIdVal = headVal[id].value;
                    headVal.key = headIdVal;
                }
            });
        }
        masterSelData[headIdVal] = {
            data: headVal,
            sel: true
        };
        item.body[bodyId].rows.map(bodys => {
            let bodyIdVal;
            if (Array.isArray(childId)) {
                childId.map(bid => {
                    if (bodys.values.hasOwnProperty(bid)) {
                        bodyIdVal = bodys.values[bid] && bodys.values[bid].value;
                        bodys.childId = bodyIdVal;
                        bodys.values.key = bodyIdVal;
                    }
                });
            }
            if (!childSelData.hasOwnProperty([headIdVal])){
                childSelData[headIdVal] = {
                    [bodyIdVal]: {
                        data: bodys,
                        sel: true
                    }
                }
            }else{
                childSelData[headIdVal][bodyIdVal] = {
                    data: bodys,
                    sel: true
                }
            }
        });
    }); 
    this.setState({
        transferTable: this.state.transferTable
    })
}
